package com.itheima.task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class SetmealTask {

    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 每天凌晨1点，清理垃圾图片
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void cleanUpGarbageImages() {
        //获取Redis中套餐图片名集合与Redis中套餐图片名集合的交集
        Set<String> intersect = redisTemplate.opsForSet().intersect(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        // 获取Redis中所有套餐图片名集合的成员
        Set<String> members = redisTemplate.opsForSet().members(RedisConstant.SETMEAL_PIC_RESOURCES);
        // 遍历Redis中的图片名集合，清理不在交集内的图片
        for (Object member : members) {
            if (!intersect.contains(member)) {
                aliOssUtil.delete((String) member);
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, member);
            }
        }
    }

}
